package com.gnerv.sylvanas.module.datasource.service.impl;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.YmlDynamicDataSourceProvider;
import com.gnerv.sylvanas.module.datasource.autoconfigure.FrameworkPluginDatasourceConfigProperties;
import com.gnerv.sylvanas.module.datasource.service.DataSourceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * 多数据源服务类
 *
 * @author Gnerv LiGen
 */
@Slf4j
@Service
public class DynamicDataSourceService implements DataSourceService {

    @Resource
    private FrameworkPluginDatasourceConfigProperties frameworkPluginDatasourceConfigProperties;

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Resource
    private DefaultDataSourceCreator defaultDataSourceCreator;

    @Resource
    private List<AbstractDataSourceProvider> dataSourceProviderList;
    @Override
    public boolean add(String poolName, DataSource dataSource) {
        dynamicRoutingDataSource.addDataSource(poolName, dataSource);
        return true;
    }

    public boolean add(DataSourceProperty dataSourceProperty) {
        DataSource dataSource = defaultDataSourceCreator.createDataSource(dataSourceProperty);
        return add(dataSourceProperty.getPoolName(), dataSource);
    }

    @Override
    public boolean remove(String name) {
        dynamicRoutingDataSource.removeDataSource(name);
        return true;
    }

    @Override
    public void reload() {
        for (AbstractDataSourceProvider abstractDataSourceProvider : dataSourceProviderList) {
            if (abstractDataSourceProvider instanceof YmlDynamicDataSourceProvider) {
                YmlDynamicDataSourceProvider ymlDynamicDataSourceProvider = new YmlDynamicDataSourceProvider(defaultDataSourceCreator,
                        frameworkPluginDatasourceConfigProperties.getDatasource());
                Map<String, DataSource> stringDataSourceMap = ymlDynamicDataSourceProvider.loadDataSources();
                for (Map.Entry<String, DataSource> dataSourceEntry : stringDataSourceMap.entrySet()) {
                    add(dataSourceEntry.getKey(), dataSourceEntry.getValue());
                }
            }
        }
    }

}
